package com.jsh.erp.service.userBusiness;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.jsh.erp.constants.BusinessConstants;
import com.jsh.erp.constants.ExceptionConstants;
import com.jsh.erp.datasource.entities.*;
import com.jsh.erp.datasource.mappers.UserBusinessMapper;
import com.jsh.erp.datasource.mappers.UserBusinessMapperEx;
import com.jsh.erp.exception.BusinessRunTimeException;
import com.jsh.erp.exception.JshException;
import com.jsh.erp.service.CommonQueryManager;
import com.jsh.erp.service.functions.FunctionService;
import com.jsh.erp.service.log.LogService;
import com.jsh.erp.service.systemConfig.SystemConfigService;
import com.jsh.erp.service.user.UserService;
import com.jsh.erp.utils.IdUtils;
import com.jsh.erp.utils.StringUtil;
import com.jsh.erp.utils.Tools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Service
public class UserBusinessService {
    private Logger logger = LoggerFactory.getLogger(UserBusinessService.class);

    @Resource
    private UserBusinessMapper userBusinessMapper;
    @Resource
    private UserBusinessMapperEx userBusinessMapperEx;
    @Resource
    private LogService logService;
    @Resource
    private UserService userService;
    @Resource
    private FunctionService functionService;
    @Resource
    private SystemConfigService systemConfigService;
    @Resource
    private CommonQueryManager configResourceManager;


    public UserBusiness getUserBusiness(String id)throws Exception {
        UserBusiness result=null;
        try{
            result=userBusinessMapper.selectByPrimaryKey(id);
        }catch(Exception e){
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    public List<UserBusiness> getUserBusiness()throws Exception {
        UserBusinessExample example = new UserBusinessExample();
        example.createCriteria().andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        List<UserBusiness> list=null;
        try{
            list=userBusinessMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int insertUserBusiness(JSONObject obj, HttpServletRequest request) throws Exception {
        UserBusiness userBusiness = JSONObject.parseObject(obj.toJSONString(), UserBusiness.class);
        userBusiness.setUploadFlag("0");
        userBusiness.setId(IdUtils.getUUID());
        int result=0;
        try{
            String token = "";
            if(request!=null) {
                token = request.getHeader("X-Access-Token");
                String tenantId = Tools.getTenantIdByToken(token);
                if(!StringUtil.isEmpty(tenantId)) {
                    userBusiness.setTenantId(tenantId);
                }
            }
            String value = userBusiness.getValue();
            String newValue = value.replaceAll(",","\\]\\[");
            newValue = newValue.replaceAll("\\[0\\]","").replaceAll("\\[\\]","");
            newValue=newValue.replaceAll("\"", "");
            userBusiness.setValue(newValue);
            result=userBusinessMapper.insertSelective(userBusiness);
            logService.insertLog("关联关系", BusinessConstants.LOG_OPERATION_TYPE_ADD, request);
        }catch(Exception e){
            JshException.writeFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int updateUserBusiness(JSONObject obj, HttpServletRequest request) throws Exception {
        UserBusiness userBusiness = JSONObject.parseObject(obj.toJSONString(), UserBusiness.class);
        userBusiness.setUploadFlag("0");
        int result=0;
        try{
            String value = userBusiness.getValue();
            String newValue = value.replaceAll(",","\\]\\[");
            newValue = newValue.replaceAll("\\[0\\]","").replaceAll("\\[\\]","");
            newValue=newValue.replaceAll("\"", "");
            userBusiness.setValue(newValue);
            result=userBusinessMapper.updateByPrimaryKeySelective(userBusiness);
            logService.insertLog("关联关系", BusinessConstants.LOG_OPERATION_TYPE_EDIT, request);
        }catch(Exception e){
            JshException.writeFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int deleteUserBusiness(String id, HttpServletRequest request)throws Exception {
        return batchDeleteUserBusinessByIds(id.toString());
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int batchDeleteUserBusiness(String ids, HttpServletRequest request)throws Exception {
        return batchDeleteUserBusinessByIds(ids);
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int batchDeleteUserBusinessByIds(String ids) throws Exception{
        logService.insertLog("关联关系",
                new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_DELETE).append(ids).toString(),
                StringUtil.getRequest());
        User userInfo=userService.getCurrentUser();
        String [] idArray=ids.split(",");
        int result=0;
        try{
            result=  userBusinessMapperEx.batchDeleteUserBusinessByIds(new Date(),userInfo==null?null:userInfo.getId(),idArray);
        }catch(Exception e){
            JshException.writeFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

     public int checkIsNameExist(String id, String name) throws Exception{
        return 1;
    }

    public List<UserBusiness> getBasicData(String keyId, String type)throws Exception{
        List<UserBusiness> list=null;
        try{
            UserBusinessExample example = new UserBusinessExample();
            example.createCriteria().andKeyIdEqualTo(keyId).andTypeEqualTo(type)
                    .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
            list= userBusinessMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }

    public List<UserBusiness> getListBy(String keyId, String type)throws Exception{
        List<UserBusiness> list=null;
        try{
            UserBusinessExample example = new UserBusinessExample();
            example.createCriteria().andKeyIdEqualTo(keyId).andTypeEqualTo(type)
                    .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
            list= userBusinessMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }

    public String getUBValueByTypeAndKeyId(String type, String keyId) throws Exception {
        String ubValue = "";
        List<UserBusiness> ubList = getBasicData(keyId, type);
        if(ubList!=null && ubList.size()>0) {
            ubValue = ubList.get(0).getValue();
        }
        return ubValue;
    }

    public String checkIsValueExist(String type, String keyId)throws Exception {
        UserBusinessExample example = new UserBusinessExample();
        example.createCriteria().andTypeEqualTo(type).andKeyIdEqualTo(keyId)
                .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        List<UserBusiness> list=null;
        try{
            list= userBusinessMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        String id = null;
        if(list!=null&&list.size() > 0) {
            id = list.get(0).getId();
        }
        return id;
    }
    /**
    * @Author: wy
    * @Description: 校检流程配置的分配权限
    * @DateTime: 2022/7/30 9:56
    * @Params:
    * @Return
    */
    public String checkIsConfigValueExist(String type, String keyId,String value,HttpServletRequest request)throws Exception {
        UserBusinessExample example = new UserBusinessExample();
        String newValue = value.replaceAll(",","\\],\\[");
        newValue = newValue.replaceAll("\\[0\\]","").replaceAll("\\[\\]","");
        newValue=newValue.replaceAll("\"", "");
        String[] result=newValue.split(",");
        String lanCode = systemConfigService.getLanCode();
        for (int i = 0; i <result.length ; i++) {
            String val= result[i];
            if (!StringUtils.isEmpty(val)){
                String token = request.getHeader("X-Access-Token");
                String tenantId = Tools.getTenantIdByToken(token);
                example.createCriteria().andTypeEqualTo(type).andValueLike("%"+val+"%")
                        .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED).andTenantIdEqualTo(tenantId);
                List<UserBusiness> userBusinesses = userBusinessMapper.selectByExample(example);
                if (userBusinesses.size() > 0) {
                    UserBusiness userBusiness = userBusinesses.get(0);
                    if (!userBusiness.getKeyId().equals(keyId)){
                        throw new BusinessRunTimeException(ExceptionConstants.DATA_READ_FAIL_CODE,
                                "zh".equals(lanCode) ? "模块已存在，其他流程中" :"Module already exists in another flow");
                    }
                }else {
                    example.clear();
                }
            }
        }
        UserBusinessExample example1 = new UserBusinessExample();
        example1.createCriteria().andTypeEqualTo(type).andKeyIdEqualTo(keyId)
                .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        List<UserBusiness> list=null;
        try{
            list= userBusinessMapper.selectByExample(example1);
        }catch(Exception e){
            JshException.readFail(logger, e, lanCode);
        }
        String id = null;
        if(list!=null&&list.size() > 0) {
            id = list.get(0).getId();
        }
        return id;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int updateBtnStr(String keyId, String type, String btnStr) throws Exception{
        logService.insertLog("关联关系",
                new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_EDIT).append("角色的按钮权限").toString(),
                StringUtil.getRequest());
        UserBusiness userBusiness = new UserBusiness();
        userBusiness.setBtnStr(btnStr);
        userBusiness.setUploadFlag("0");
        UserBusinessExample example = new UserBusinessExample();
        example.createCriteria().andKeyIdEqualTo(keyId).andTypeEqualTo(type);
        int result=0;
        try{
            result=  userBusinessMapper.updateByExampleSelective(userBusiness, example);
        }catch(Exception e){
            JshException.writeFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    public String checkValueExist(String type, String value,HttpServletRequest request)throws Exception {
        UserBusinessExample example = new UserBusinessExample();
        String token = request.getHeader("X-Access-Token");
        String tenantId = Tools.getTenantIdByToken(token);
        if (StringUtil.isEmpty(tenantId)){
            return null;
        }
        example.createCriteria().andTypeEqualTo(type).andValueLike("%"+value+"%")
                .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED)
                .andTenantIdEqualTo(tenantId);
        List<UserBusiness> list=null;
        try{
            list= userBusinessMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        String id = null;
        if(list!=null&&list.size() > 0) {
            id = list.get(0).getKeyId();
        }
        return id;
    }

    public Integer saveWarning(Integer day,String keyId) {
        try {
            User user = userService.getCurrentUser();
            UserBusinessExample example = new UserBusinessExample();
            example.createCriteria().andTypeEqualTo("warning").andKeyIdEqualTo(keyId).andTenantIdEqualTo(user.getTenantId())
                    .andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
            List<UserBusiness> list= userBusinessMapper.selectByExample(example);
            if(day!=null){
                if (list.size()>0){
                    if(!list.get(0).getValue().equals(day.toString())){
                        list.get(0).setValue(day.toString());
                        list.get(0).setUploadFlag("0");
                        userBusinessMapper.updateByPrimaryKeySelective(list.get(0));
                    }
                }else {
                    UserBusiness userBusiness = new UserBusiness();
                    userBusiness.setId(IdUtils.getUUID());
                    userBusiness.setType("warning");
                    userBusiness.setKeyId(keyId);
                    userBusiness.setValue(day.toString());
                    userBusiness.setTenantId(user.getTenantId());
                    userBusiness.setUploadFlag("0");
                    userBusinessMapper.insertSelective(userBusiness);
                }
                return day;
            }else {
                if (list.size()>0){
                    day = Integer.parseInt(list.get(0).getValue());
                }else {
                    day = 0;
                }
                return day;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return 1;
    }
}
